package cn.demomaster.quickui;

import android.app.Application;
import android.content.Context;
import android.content.res.Configuration;
import android.database.sqlite.SQLiteDatabase;
import android.os.Environment;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;

import androidx.multidex.MultiDex;

import com.demomaster.quickcompat.content.QuickSharedPreferences;
import com.demomaster.quickcompat.widget.toast.QdToast;

import java.io.File;

import cn.demomaster.quickdb.QuickDb;
import cn.demomaster.quickdb.listener.UpgradeInterface;
import cn.demomaster.quicklogger.QdLog;
import cn.demomaster.quicklogger.config.LogConfigBuilder;
import cn.demomaster.quickrouter.manager.QuickActivityManager;
import cn.demomaster.quickui.constant.AppConfig;
import cn.demomaster.quickui.ui.error.LogViewerActivity;
import cn.demomaster.quickui.util.CrashHandler;
import cn.demomaster.quickui.util.xml.QDSaxXml;

public class QuickApplication extends Application implements UpgradeInterface {

    private static QuickApplication instance = null;
    public Handler handler;
    public static QuickApplication getInstance() {
        return instance;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        instance = this;
        handler = new Handler();
        QdToast.setContext(this);
        AppConfig.getInstance().load(this, "config/project.json");
        //String logPath = (String) AppConfig.getInstance().getConfigMap().get("LogFilePath");
        /*if(!TextUtils.isEmpty(logPath)) {
            QdLog.init(this, logPath);
        }*/
        //QdLog.init(this,null);
        LogConfigBuilder configBuilder = new LogConfigBuilder(this);
        configBuilder.setSaveExternalStorageBeforeAndroidQ(false);
        configBuilder.setSaveInternalSoragePath("/log/");
        configBuilder.setSaveExternalStoragePath(new File(Environment.getExternalStorageDirectory(),"quickui/log"));
        //QdLog.init(this, configBuilder.build());
        QdLog.init(this,configBuilder.build());
        //QdLog.i(TAG, "包名：" + getPackageName() + ",myPid=" + android.os.Process.myPid()+",uid="+QDAppInfoUtil.getUidByPackageName(this,getPackageName()));
        
        //初始化全局SharedPreferences
        QuickSharedPreferences.init(this);
        //activity管理监听
        QuickActivityManager.getInstance().init(this);
        //LifecycleManager.getInstance().init(this);

      /*  ActivityManager.RunningAppProcessInfo processInfo = QDProcessUtil.getProcessInfo(getApplicationContext(), android.os.Process.myPid());
        if (TextUtils.isEmpty(processInfo.processName) || !getPackageName().equals(processInfo.processName)) {
            QdLog.e(TAG, getPackageName() + "进程[" + android.os.Process.myPid() + "]已存在无需重复初始化");
            return;
        }*/

        //NotifycationHelper.getInstance().init(this);

        //QDSaxXml.parseXmlAssets(this, "config/test.xml", cn.demomaster.quickui.util.xml.Article.class, null);
        //QDSaxXml.parseXmlAssets(this, "config/test2.xml", cn.demomaster.quickui.util.xml.AppConfig.class, null);
        QDSaxXml.parseXmlAssets(this, "config/project.xml", cn.demomaster.quickui.util.xml.AppConfig.class, result -> QdLog.println("配置文件初始化完成" + result));
        
        //处理崩溃日志
        initCrash();
        //DoraemonKit.install(this);
        /*if (isDebug(this)) {
           ServiceHelper.showWindow(this,DebugFloatingService.class);
        }*/

        // 获取当前设备的 Configuration
        Configuration configuration = getResources().getConfiguration();

        // 获取屏幕宽度匹配的 sw 值
        int smallestScreenWidthDp = configuration.smallestScreenWidthDp;
        //Thread.currentThread().setUncaughtExceptionHandler();

        // 打印屏幕宽度匹配的 sw 值
        Log.d("Device SW", "Smallest Screen Width: " + smallestScreenWidthDp + "dp");
    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(base);
    }

    public QuickDb dbHelper;
    
    /**
     * 初始化本地数据库
     * @return
     */
    public QuickDb getDbHelper() {
        if (dbHelper == null) {
            String dbpath = null;
            if (AppConfig.getInstance().getConfigMap(getApplicationContext()).containsKey("dbpath")) {
                dbpath = (String) AppConfig.getInstance().getConfigMap(getApplicationContext()).get("dbpath");
            }

            if (!TextUtils.isEmpty(dbpath)) {
                dbHelper = new QuickDb(this, dbpath, null, 7, this);
                // dbHelper = new QuickDb(this, dbpath, null, 7, this);
            }
        }
        return dbHelper;
    }
    
    /**
     * 处理异常捕获
     */
    public void initCrash() {
        if (BuildConfig.DEBUG) {
            /*Class errorReportActivity = AppConfig.getInstance().getClassFromClassMap("errorReportActivity");
            QdLog.println("errorReportActivity="+errorReportActivity);*/
            CrashHandler.getInstance().init(this, LogViewerActivity.class);//ErrorCrashActivity.class);
        }else {
            CrashHandler.getInstance().init(this, null);
            CrashHandler.getInstance().setCrashDealType(CrashHandler.CrashDealType.savelog);
        }
    }

    /**
     * 数据库更新触发
     *
     * @param db
     * @param oldVersion
     * @param newVersion
     */
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }


}
